package com.hk.demo.player.grid;

import android.content.Context;

import com.hk.player.core.MonitorMediaData;
import com.zhoug.common.utils.LogUtils;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.viewpager2.widget.ViewPager2;

import static com.hk.demo.player.grid.GridMode.MODE_1X1;

/**
 * @author: zhoug
 * @since: 2025-08-18
 */
public class VideoPagerManager {
    private static final String TAG = ">>>VideoPagerManager";
    // 布局模式常量
    private int mCurrentMode = MODE_1X1; // 默认单屏模式
    private Context mContext;
    private Lifecycle mLifecycle;
    private Listener mListener;
    private ViewPager2 mViewPager;
    private VideoPagerAdapter mAdapter;
    private int mCurrentPlayPosition;

    public VideoPagerManager(@NonNull Context context, Lifecycle lifecycle, @NonNull ViewPager2 viewPager) {
        this.mContext = context;
        this.mLifecycle = lifecycle;
        this.mViewPager = viewPager;
        init();
    }

    private void init() {
        this.mAdapter = new VideoPagerAdapter(mContext, mCurrentMode, mLifecycle);
        this.mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.registerOnPageChangeCallback(mOnPageChangeCallback);

        if (mLifecycle != null) {
            mLifecycle.addObserver(new DefaultLifecycleObserver() {
                @Override
                public void onDestroy(@NonNull LifecycleOwner owner) {
                    mViewPager.unregisterOnPageChangeCallback(mOnPageChangeCallback);
                }
            });
        }
    }

    /**
     * 页面切换回掉
     */
    private final ViewPager2.OnPageChangeCallback mOnPageChangeCallback = new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            LogUtils.d(TAG, "onPageSelected:" + position);
            mAdapter.startPlay(position);
        }
    };


    /**
     * 切换网格模式,按顺序切换到下一个,到了最后一个则切换成第一个
     */
    public void toggleGridMode() {
        List<Integer> modes = GridMode.getModes();
        int curIndex = modes.indexOf(mCurrentMode);
        if (curIndex < modes.size() - 1) {
            curIndex++;
        } else {
            curIndex = 0;
        }
        String oldModeName = GridMode.getModeName(mCurrentMode);
        mCurrentMode = modes.get(curIndex);
        String newModeName = GridMode.getModeName(mCurrentMode);
        LogUtils.d(TAG, "toggleGridMode:" + oldModeName + "->" + newModeName);
        if (mListener != null) {
            mListener.onGridModeChange(mCurrentMode);
        }
        // 保存当前播放位置
        int currentPosition = mViewPager.getCurrentItem();
        // 更新适配器
        mAdapter.setGridMode(mCurrentMode);
        mViewPager.setAdapter(mAdapter);

        // 计算并跳转到正确的页面位置
        int newPosition = calculateNewPosition(currentPosition, mCurrentMode);
        mViewPager.setCurrentItem(newPosition, false);

    }

    /**
     * 根据当前ViewPager显示页面的第一个计算新布局中同一个位置的所在页
     *
     * @param oldPosition ViewPager切换模式之前显示的页
     * @param newMode     新的网格模式
     * @return ViewPager切换模式后需要显示的页
     */
    private int calculateNewPosition(int oldPosition, int newMode) {
        int oldItemsPerPage = getItemsPerPage(mAdapter.getPreviousMode());
        int newItemsPerPage = getItemsPerPage(newMode);

        int firstItemIndex = oldPosition * oldItemsPerPage;
        return firstItemIndex / newItemsPerPage;
    }

    /**
     * 根据GridMode计算每页数据条数
     *
     * @param mode
     * @return 每页数据条数
     */
    private int getItemsPerPage(int mode) {
        return GridMode.getItemsPerPage(mode);
    }

    /**
     * 设置视频数据
     *
     * @param data 视频数据
     */
    public void setData(List<MonitorMediaData> data) {
        mAdapter.setData(data);
    }

    public void notifyDataSetChanged() {
        mAdapter.notifyDataSetChanged();
    }

    public void requestLayout() {
        //无法保存正在播放的视频的状态
        mViewPager.setAdapter(mAdapter);
    }


    /**
     * 设置监听器
     *
     * @param listener Listener
     */
    public void setListener(Listener listener) {
        this.mListener = listener;
    }

    public interface Listener {
        /**
         * 网格布局模式切换后回掉
         *
         * @param gridMode {@link GridMode}
         */
        void onGridModeChange(int gridMode);
    }


}
